package org.fcitmuk.mobilehrs.forms;

import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;
import javax.microedition.midlet.MIDlet;

import org.fcitmuk.communication.ConnectionParameter;
import org.fcitmuk.communication.TransportLayer;
import org.fcitmuk.epihandy.EpihandyConstants;
import org.fcitmuk.epihandy.midp.forms.FormManager;
import org.fcitmuk.epihandy.midp.forms.LogonListener;
import org.fcitmuk.epihandy.midp.forms.UserManager;
import org.fcitmuk.midp.db.util.Settings;
import org.fcitmuk.util.AlertMessage;
import org.fcitmuk.util.DefaultCommands;

public class MainForm  extends MIDlet  implements CommandListener,LogonListener{

	/** Reference to the current display. */
	private Display display;
	
	/** The main menu screen. */   
	private List mainList;
	
	/** Index for search patient menu item. */
	private static final int INDEX_SEARCH_HOUSEHOLD = 0;
	
	/** Index for search patient menu item. */
	private static final int INDEX_SEARCH_LOCATION = 1;
	
	/** Index for new patient menu item. */
	private static final int INDEX_NEW_HOUSEHOLD = 2;
	
	private static final int INDEX_NEW_LOCATION = 3;
	
	/** Index for downloading forms menu item. */
	private static final int INDEX_DOWNLOAD_FORMS = 4;
	
	/** Index for downloading patients menu item. */
	private static final int INDEX_DOWNLOAD_DSS_DATA = 5;
	
	/** Index for uploading data menu item. */
	private static final int INDEX_UPLOAD_DATA = 6;
	
	/** Index for specifying settings like server connection parameters. */
	private static final int INDEX_SETTINGS = 7;
	
	/** Index for selecting a study menu item. */
	private static final int INDEX_LOGOUT = 8;
	
	/** Application tittle. */
	private static final String TITLE = "MobileHRS";
	
	/** Status to download a list of patients from the server. */
	public static final byte ACTION_DOWNLOAD_DSS_DATA = 6;

	/** Reference to epihandy form manager. */
	private FormManager formMgr;
	
	/** Reference to the transportLayer. */
	private TransportLayer transportLayer;
	
	private AlertMessage alertMsg;
	
	/** No alert is currently displayed. */
	private static final byte CA_NONE = -1;
		
	private static byte currentAction = CA_NONE;

	/** The user manager object. */
	private UserManager userMgr;
	
	/** The current selected index of the main menu. For now, this is used to keep track of
	 * the user's action to return to after successfully logging in. This happens when the user
	 * tries to do something before logging in, and the logon mananer intervenes by requiring the
	 * user to first login. This happens after downloading forms because a new list of users is got
	 * which makes void the current users info. */
	private int selectedIndex = EpihandyConstants.NO_SELECTION;
	
	private static final String KEY_LAST_SELECTED_MAIN_MENU_ITEM =  "LAST_SELECTED_MAIN_MENU_ITEM";
	private static final String STORAGE_NAME_SETTINGS = "STORAGE_NAME_OPENMRS_SETTINGS";
	
	private static String NAME_DSS_DATA_DOWNLOAD_URL = "dss data download url:";
	
	/** Construct the main UI midlet. */
	public MainForm() {
		super();
		
		display = Display.getDisplay(this);
		
		initMainList();
		
		transportLayer = new TransportLayer(/*new EpihandyTransportLayer().getClass()*/);
		transportLayer.setDisplay(display);
		transportLayer.setPrevScreen(mainList);
		transportLayer.setDefaultCommnucationParameter(TransportLayer.KEY_BLUETOOTH_SERVER_ID, /*"F0E0D0C0B0A000908070605040302010"*/ "F0E0D0C0B0A000908070605040301111");
		transportLayer.setDefaultCommnucationParameter(TransportLayer.KEY_HTTP_URL, "");
		transportLayer.setDefaultCommnucationParameter(TransportLayer.KEY_SMS_DESTINATION_ADDRESS,"sms://+256712330386"); //256782380638 "sms://+256782380638:1234"
		transportLayer.setDefaultCommnucationParameter(TransportLayer.KEY_SMS_SOURCE_ADDRESS,"sms://:1234"); 
		transportLayer.addConnectionParameter(new ConnectionParameter(TransportLayer.CON_TYPE_HTTP,NAME_DSS_DATA_DOWNLOAD_URL,"http://localhost:8080/openmrs/module/xforms/patientDownload.form?downloadPatients=true"));
		//transportLayer.addConnectionParameter(new ConnectionParameter(1,"IMEI",System.getProperty("com.nokia.imei")));
		
		//formMgr = new FormManager(TITLE,display,this, mainList,transportLayer,this);
		
		//alertMsg = new AlertMessage(this.display, TITLE, this.mainList,this);
	}
	
	private void initMainList(){
		//TODO These strings may need to be localised.
		mainList = new List(TITLE, Choice.IMPLICIT);
		mainList.insert(INDEX_SEARCH_HOUSEHOLD, "Search HouseHold", null);
		mainList.insert(INDEX_SEARCH_LOCATION, "Search Location", null);
		mainList.insert(INDEX_NEW_HOUSEHOLD, "New HouseHold", null);
		mainList.insert(INDEX_NEW_LOCATION, "New Location", null);
		mainList.insert(INDEX_DOWNLOAD_FORMS, "Download Forms", null);
		mainList.insert(INDEX_DOWNLOAD_DSS_DATA, "Download DSS Data", null);
		mainList.insert(INDEX_UPLOAD_DATA, "Upload Data", null);
		mainList.insert(INDEX_SETTINGS, "Settings", null);
		mainList.insert(INDEX_LOGOUT, "Logout", null);
		
		mainList.addCommand(DefaultCommands.cmdOk);
		mainList.addCommand(DefaultCommands.cmdExit);
		
		Settings settings = new Settings(STORAGE_NAME_SETTINGS,true);
		String val = settings.getSetting(KEY_LAST_SELECTED_MAIN_MENU_ITEM);
		if(val != null)
			mainList.setSelectedIndex(Integer.parseInt(val),true);
		
		mainList.setCommandListener(this);
	}

	protected void destroyApp(boolean arg0) {
		
	}

	protected void pauseApp() {
		
	}

	protected void startApp() {
		userMgr = new UserManager(display,mainList,TITLE,this);
		userMgr.logOn();
		//formMgr.setUserManager(userMgr);
		//display.setCurrent(mainList);
		//System.out.println(org.fcitmuk.db.util.PersistentHelper.getSize(StudyDefTest.getTestStudyDef()));
		//System.out.println(getAppProperty("SMS-Port"));
	}
	
	public boolean onLoggedOn(){
		boolean displayPrevScreen = false;
		if(selectedIndex != EpihandyConstants.NO_SELECTION)
			;//handleMainListSelectCommand(selectedIndex);
		else
			displayPrevScreen = true;
		
		return displayPrevScreen;
	}
	
	public void onLogonCancel(){
		if(selectedIndex == EpihandyConstants.NO_SELECTION)
			handledExitCommand();
		else
			display.setCurrent(mainList);
	}
	
	private void logout(){
		/** If this is not reset, after loggin in, we shall wrongly execute an action that
		 * the user did not intend to.*/
		this.selectedIndex = EpihandyConstants.NO_SELECTION;
		
		userMgr.logOut();
		userMgr.logOn();
	}
	
	/**
	 * Handles the exit command.
	 *
	 */
	private void handledExitCommand(){
		destroyApp(false);
        notifyDestroyed();
	}
	
	/**
	 * Processes the command events.
	 * 
	 * @param c - the issued command.
	 * @param d - the screen object the command was issued for.
	 */
	public void commandAction(Command c, Displayable d) {
		try{
	        if (c == DefaultCommands.cmdExit)
	        	handledExitCommand();
	        else if(c == List.SELECT_COMMAND)
	        	;//handleListSelectCommand(((List)d).getSelectedIndex());
	        else if(c == DefaultCommands.cmdCancel)
	        	;//handledCancelCommand(d);
	        else if(c == DefaultCommands.cmdOk)
	        	;//handleOkCommand(d);
	        else if(c == DefaultCommands.cmdBack)
	        	;//handledBackCommand(d);
		}
		catch(Exception e){
			alertMsg.showError(e.getMessage());
			e.printStackTrace();
		}
    }
}
